package com.ruoyi.ip.handler;

import com.ruoyi.ip.util.HttpUtils;
import com.ruoyi.ip.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class Ip138Handler implements IpHandler
{
    public static final String IP_URL = "https://www.ip138.com/iplookup.php";

    @Override
    public Map<String, Object> getRegion(String ip)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("address", getRealAddressByIP(ip));
        return map;
    }

    public static String getRealAddressByIP(String ip)
    {
        String address = "XX XX";
        if (IpUtil.internalIp(ip))
        {
            return "内网IP";
        }
        String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
        try
        {
            String regex = "<span>[\\u4E00-\\u9FA5]*<a[^<]*";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(rspStr);

            if (matcher.find())
            {
                String  resultstr = matcher.group();
                resultstr = resultstr.replaceAll("<.*?>", "");
                return resultstr;
            }
            else
            {
                log.error("获取地理位置异常");
            }
        }
        catch (Exception e)
        {
            System.out.println(e.toString());
            log.error("获取地理位置异常 {}", ip);
        }
        return address;
    }
}
